package com.www.applyword.main;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.ParamsBean;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.ui.home.AgreementActivity;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : huang
 * date   : 2019/10/26 0026 9:52
 * version: 1.0
 */
public class RegisterActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password2)
    EditText etPassword2;
    @BindView(R.id.sb_register)
    SuperButton sbRegister;
    @BindView(R.id.tv_registered)
    TextView tvRegistered;
    @BindView(R.id.et_nickName)
    EditText etNickName;
    @BindView(R.id.sb_code)
    SuperButton sbCode;
    @BindView(R.id.cb4)
    CheckBox cb4;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;

    private String url = Constants.REGISTER;

    private VerificationCodeCountTimer verificationCodeCountTimer;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.register_activity);
        setTitle("注册");
        initView();
    }


    private void initView() {
        verificationCodeCountTimer = new VerificationCodeCountTimer(61100, 1000);
        tvAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
    }

    @Override
    protected void loadData() {

    }


    @OnClick({R.id.et_code, R.id.sb_register, R.id.tv_registered, R.id.sb_code,R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_code:

                break;
            case R.id.sb_code:
                getCode();
                break;
            case R.id.sb_register:
                if (TextUtils.isEmpty(etNickName.getText().toString())) {
                    Utils.showToastSafe("请输入昵称");
                    return;
                }
                if (!Utils.isPhoneNumber(etPhone.getText().toString())) {
                    Utils.showToastSafe("请输入正确的手机号码");
                    return;
                }
                if (TextUtils.isEmpty(etCode.getText().toString())) {
                    Utils.showToastSafe("请输入验证码");
                    return;
                }

                if (TextUtils.isEmpty(etPassword.getText().toString().trim())) {
                    Utils.showToastSafe("请输入6-12位密码");
                    return;
                }

                if (etPassword2.getText().toString().length() < 6) {
                    Utils.showToastSafe("请再次输入6-12位密码");
                    return;
                }

                if (etPassword.getText().toString().trim().equals(etPassword2.getText().toString().trim())) {

                } else {
                    Utils.showToastSafe("2次输入的密码不一致");
                    return;
                }

                if (!cb4.isChecked()){
                    Utils.showToastSafe("请阅读并同意并勾选注册协议");
                    return;
                }

                register();
                break;
            case R.id.tv_registered:
                finish();
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(this, AgreementActivity.class).putExtra("type", 0));
                break;
            default:
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }


    class VerificationCodeCountTimer extends CountDownTimer {

        private VerificationCodeCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int time = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
            // sbCode.setTextColor(getResources().getColor(R.color.color_yellow2));
            sbCode.setText(time + "s");
        }

        @Override
        public void onFinish() {
            sbCode.setText("获取验证码");
        }
    }

    private void getCode() {
        if (!Utils.isPhoneNumber(etPhone.getText().toString())) {
            Utils.showToastSafe("请输入正确的手机号码");
            return;
        }
        verificationCodeCountTimer.start();
        Map<String, Object> params = new HashMap<>();
        ParamsBean paramsBean = new ParamsBean();
        params.put("mobile", etPhone.getText().toString());
        params.put("appKey", paramsBean.getAppKey());
        params.put("townId", paramsBean.getTownId());
        params.put("version", paramsBean.getVersion());
        params.put("versionCode", paramsBean.getVersionCode());
        params.put("channel", paramsBean.getChannel());
        params.put("downloadSource", paramsBean.getDownloadSource());
        params.put("deviceId", paramsBean.getDeviceId());
        params.put("osVersionName", paramsBean.getOsVersionName());
        params.put("timestamp", paramsBean.getTimestamp());
        params.put("sign", paramsBean.getSign());
        params.put("model", paramsBean.getModel());
        params.put("brand", paramsBean.getBrand());
        params.put("product", paramsBean.getProduct());
        params.put("sdkversion", paramsBean.getSdkversion());
        params.put("imei", paramsBean.getImei());
        params.put("androidid", paramsBean.getAndroidid());
        HttpClient.post(RegisterActivity.this, Constants.verifyCode, params, new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
                 // etCode.setText(result);
            }
        });
    }

    private void register() {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> params2 = new HashMap<>();
        params.put("Mobile", etPhone.getText().toString());
        params.put("Pwd", etPassword.getText().toString());
        params.put("Code", etCode.getText().toString());
        params.put("Name", etNickName.getText().toString());
        if (params != null && params.size() > 0) {
            url += "?";
            for (String key : params.keySet()) {
                String value = (String) params.get(key);
                url += key + "=" + value + "&";
            }
            url = url.substring(0, url.length() - 1);
        }

        HttpClient.post(RegisterActivity.this, url, params2, new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                String userSig = result.getUserSig();
                SPUtil.put(Constants.USERID, result.getUser().getUserInfo_ID());
                SPUtil.put(Constants.USERSIG, userSig);
                SPUtil.put(Constants.PHONE, result.getUser().getUserInfo_Mobile());
                finish();
              /*  TUIKit.login(result.getUser().getUserInfo_Mobile(),userSig, new IUIKitCallBack() {
                    @Override
                    public void onSuccess(Object data) {
                        MessageEvent messageEvent = new MessageEvent();
                        messageEvent.setMessageKey(EventConstants.REGISTER);
                        EventBus.getDefault().post(messageEvent);

                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        //错误码 code 和错误描述 desc，可用于定位请求失败原因
                        //错误码 code 列表请参见错误码表
                        Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                        Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                    }
                });*/
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verificationCodeCountTimer != null) {
            verificationCodeCountTimer.cancel();
        }
    }
}
